'''
Author: 码上talk|RC
Date: 2020-09-11 14:13:30
LastEditTime: 2021-06-19 17:32:21
LastEditors: 码上talk|RC
Description:
FilePath: /server-py/libs/excel_lib.py
微信:  13680065830
邮箱:  3189482282@qq.com
oops: Just do what I think it is right
'''
import time
import pandas as pd
from copy import deepcopy

from utils.path_util import PathUtil
from utils.oss_util import OssUtil


class ExcelLib():
    def __init__(self, config={}):
        self._default_config = {}
        self._init_time = time.time()
        self.config = {}
        self._init_config(config)

    def _init_config(self, config):
        self.config = deepcopy(self._default_config)
        self.config.update(config)

    def load(self, filename):
        self.path_excel = filename

    def get_json(self, headers=[]):
        df = pd.read_excel(self.path_excel)
        excel_json = []
        for i in range(len(df)):
            j = {}
            for h in headers:
                try:
                    j[h['key']] = df.iloc[i][h['name']]
                except Exception as e:
                    pass
            excel_json.append(j)
        return excel_json

    def gen_file(self, json, headers=[], config={'is_upload_to_oss': True}):
        result = {}
        file_path = PathUtil.root(
            '.tmp/excel/downlaod/') + '{filename}.xlsx'.format(filename=time.time())
        if len(headers) == 0:
            return
        lst = []
        for j in json:
            info = {}
            try:
                for h in headers:
                    info[h['key']] = j[h['key']]
            except Exception as e:
                info = {}
            lst.append(info)

        excel_list = []
        for l in lst:
            row = [None] * len(headers)
            for i, v in enumerate(headers):
                row[i] = l[v['key']]
            excel_list.append(row)
        df = pd.DataFrame(excel_list, columns=list(
            map(lambda x: x['name'], headers)))
        writer = pd.ExcelWriter(file_path, engine='xlsxwriter')
        df.to_excel(writer, sheet_name='Sheet1', index=False)
        writer.save()
        if ('is_upload_to_oss' in config):
            oss_util = OssUtil(bucket='bucketFile')
            result['oss_url'] = oss_util.upload_local_file(file_path)['url']
        return result
